package git.soulbgm.controller;
import java.util.Date;

import git.soulbgm.dao.UserRepository;
import git.soulbgm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 用户控制器
 *
 * @author SoulBGM
 * @date 2022/11/12 18:40
 */
@RestController
@RequestMapping("user")
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping
    public User save(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping
    public List<User> list(@RequestBody User user) {
        Example<User> example = Example.of(user);
        List<User> userList = userRepository.findAll(example);
        return userList;
    }

    @PutMapping
    public User edit(@RequestBody User user) {
        User sourceUser = userRepository.findById(user.getId()).get();
        String username = user.getUsername();
        if (!StringUtils.isEmpty(username)) {
            sourceUser.setUsername(username);
        }
        String password = user.getPassword();
        if (!StringUtils.isEmpty(password)) {
            sourceUser.setPassword(password);
        }
        String nickname = user.getNickname();
        if (!StringUtils.isEmpty(nickname)) {
            sourceUser.setNickname(nickname);
        }
        Date birthdate = user.getBirthdate();
        if (birthdate != null) {
            sourceUser.setBirthdate(birthdate);
        }
        userRepository.flush();
        return sourceUser;
    }

    @DeleteMapping
    public String delete(@RequestBody User user) {
        userRepository.deleteById(user.getId());
        return "success";
    }

}
